<template>
    <div>
      <h1>Product Management</h1>
  
      <!-- Add New Product -->
      <div>
        <h2>Add New Product</h2>
        <input v-model="newProduct.name" placeholder="Name" />
        <input v-model="newProduct.price" type="number" placeholder="Price" />
        <input v-model="newProduct.category" type="number" placeholder="Category" />
        <input v-model="newProduct.imageURL" placeholder="Image URL" />
        <label>
          Available:
          <input type="checkbox" v-model="newProduct.isAvailable" />
        </label>
        <button @click="addProduct">Add Product</button>
      </div>
  
      <!-- Sort and Filter Options -->
      <div>
        <h2>Sort and Filter Options</h2>
        <select v-model="sortBy" @change="fetchProducts">
          <option value="name">Name</option>
          <option value="price">Price</option>
          <option value="count">Sold Count</option>
          <option value="modifieddate">Modified Date</option>
        </select>
        <input v-model="filterCategory" type="number" placeholder="Filter by Category ID" @input="fetchProducts" />
        <label>
          Available Only:
          <input type="checkbox" v-model="filterAvailable" @change="fetchProducts" />
        </label>
      </div>
  
      <!-- Product List -->
      <div>
        <h2>Product List</h2>
        <ul>
          <li v-for="product in products" :key="product.productID">
            <img :src="product.imageURL" alt="Product Image" width="50" />
            {{ product.name }} - ${{ product.price }} - Sold: {{ product.count }}
            <button @click="deleteProduct(product.productID)">Delete</button>
            <button @click="updateProductAvailability(product.productID, !product.isAvailable)">
              {{ product.isAvailable ? 'Disable' : 'Enable' }}
            </button>
          </li>
        </ul>
      </div>
  
      <!-- Inventory Management -->
      <div>
        <h2>Inventory Management</h2>
        <ul>
          <li v-for="inventory in inventories" :key="inventory.inventoryID">
            Product ID: {{ inventory.productID }} - Stock Quantity: {{ inventory.stockQuantity }} - Last Updated: {{ inventory.lastUpdated }}
            <button @click="updateInventoryStock(inventory.inventoryID, inventory.stockQuantity + 1)">Add Stock</button>
            <button @click="updateInventoryStock(inventory.inventoryID, inventory.stockQuantity - 1)">Remove Stock</button>
          </li>
        </ul>
      </div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    name: 'ProductManagement',
    data() {
      return {
        products: [],
        newProduct: {
          name: '',
          price: 0,
          category: 1,
          imageURL: '',
          isAvailable: true,
          count: 0
        },
        sortBy: 'name',
        filterCategory: null,
        filterAvailable: false,
        inventories: []
      };
    },
    mounted() {
      this.fetchProducts();
      this.fetchInventories();
    },
    methods: {
      async fetchProducts() {
        try {
          const response = await axios.get('https://localhost:5001/api/product/sorted', {
            params: {
              sortBy: this.sortBy,
              categoryId: this.filterCategory,
              isAvailable: this.filterAvailable
            }
          });
          this.products = response.data;
        } catch (error) {
          console.error('Error fetching products:', error);
        }
      },
      async addProduct() {
        try {
          await axios.post('https://localhost:5001/api/product', this.newProduct);
          this.fetchProducts();
          this.newProduct = { name: '', price: 0, category: 1, imageURL: '', isAvailable: true, count: 0 };
        } catch (error) {
          console.error('Error adding product:', error);
        }
      },
      async deleteProduct(productId) {
        try {
          await axios.delete(`https://localhost:5001/api/product/${productId}`);
          this.fetchProducts();
        } catch (error) {
          console.error('Error deleting product:', error);
        }
      },
      async updateProductAvailability(productId, isAvailable) {
        try {
          const product = this.products.find(p => p.productID === productId);
          product.isAvailable = isAvailable;
          await axios.put(`https://localhost:5001/api/product/${productId}`, product);
          this.fetchProducts();
        } catch (error) {
          console.error('Error updating product availability:', error);
        }
      },
      async fetchInventories() {
        try {
          const response = await axios.get('https://localhost:5001/api/inventory');
          this.inventories = response.data;
        } catch (error) {
          console.error('Error fetching inventories:', error);
        }
      },
      async updateInventoryStock(inventoryId, newQuantity) {
        try {
          const inventory = this.inventories.find(i => i.inventoryID === inventoryId);
          if (newQuantity < 0) {
            console.error('Stock quantity cannot be negative');
            return;
          }
          inventory.stockQuantity = newQuantity;
          inventory.lastUpdated = new Date().toISOString();
          await axios.put(`https://localhost:5001/api/inventory/${inventoryId}`, inventory);
          this.fetchInventories();
        } catch (error) {
          console.error('Error updating inventory stock:', error);
        }
      }
    }
  };
  </script>
  
  <style scoped>
  h1 {
    font-size: 2em;
    margin-bottom: 1em;
  }
  
  h2 {
    font-size: 1.5em;
    margin-top: 1em;
  }
  
  input,
  select {
    margin: 0.5em 0.5em 0.5em 0;
  }
  
  button {
    margin-left: 0.5em;
  }
  </style>